//
//  NSString+JwTime.m
//  JwPack
//
//  Created by 陈警卫 on 2024-07-17.
//

#import "NSString+JwTime.h"

@implementation NSString (JwTime)

/// 时间戳转时钟 00:00:00
- (NSString *)jw_clockString {
    NSInteger seconds = [self integerValue];
    NSString *hour = [NSString stringWithFormat:@"%02ld", seconds/3600];
    NSString *minute = [NSString stringWithFormat:@"%02ld", (seconds%3600)/60];
    NSString *second = [NSString stringWithFormat:@"%02ld", seconds%60];
    NSString *time = [NSString stringWithFormat:@"%@:%@:%@", hour, minute, second];
    return time;
}

///  时间戳转时钟 00:00/00:00:00
- (NSString *)jw_clockFitsString {
    NSInteger seconds = [self integerValue];
    if (seconds < 3600) {
        NSString *minute = [NSString stringWithFormat:@"%02ld", (seconds%3600)/60];
        NSString *second = [NSString stringWithFormat:@"%02ld", seconds%60];
        NSString *time = [NSString stringWithFormat:@"%@:%@", minute, second];
        return time;
    } else {
        return [self jw_clockString];
    }
}

/// format字符串转时间
/// format默认 "yyyy-MM-dd HH:mm:ss"
- (NSDate *)jw_dateWithFormat:(NSString *)format {
    return [self jw_dateWithFormat:format timeZone:nil locale:nil];
}

/// format字符串转时间
/// format默认 "yyyy-MM-dd HH:mm:ss"
- (NSDate *)jw_dateWithFormat:(NSString *)format timeZone:(NSTimeZone *)timeZone locale:(NSLocale *)locale {
    NSDateFormatter *dateForm = [[NSDateFormatter alloc] init];
    if (!format) {
        format = @"yyyy-MM-dd HH:mm:ss";
    }
    if (timeZone) {
        dateForm.timeZone = timeZone;
    }
    if (locale) {
        dateForm.locale = locale;
    }
    [dateForm setDateFormat:format];
    NSDate *date = [dateForm dateFromString:self];
    return date;
}

// 时间戳转Date
- (NSDate *)jw_stampToDate {
    NSTimeInterval interval = [self doubleValue];
    // 检查时间戳是否为10位或13位
    interval = self.length == 13 ? interval/1000.0 : interval;
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];
    return date;
}

/// 时间戳转format字符串
/// format默认 "yyyy-MM-dd HH:mm:ss"
- (NSString *)jw_stampToFormat:(NSString *)format {
    NSDate *date = [self jw_stampToDate];
    NSDateFormatter *dateForm = [[NSDateFormatter alloc] init];
    if (!format) {
        format = @"yyyy-MM-dd HH:mm:ss";
    }
    [dateForm setDateFormat:format];
    NSString *dateString = [dateForm stringFromDate:date];
    return dateString;
}

/// 时间戳
+ (NSString *)jw_timestamp {
    return [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]];
}

/// 时钟戳
+ (NSString *)jw_dateFmtString {
    NSDateFormatter *formatter  = [[NSDateFormatter alloc] init];
    formatter.dateFormat  = @"yyyyMMddHHmmssSSS";
    NSString *datefrom = [formatter stringFromDate:[NSDate date]];
    return datefrom;
}


@end
